package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;



    /**
     * 查看订单数据
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> get(int page, int pageSize, String number,
                       @DateTimeFormat(pattern = "yy-MM-dd HH:mm:ss") Date beginTime,
                       @DateTimeFormat(pattern = "yy-MM-dd HH:mm:ss")Date endTime){
        log.info("page:{},pageSize:{},number:{},beginTime:{},endTime:{}", page, pageSize, number, beginTime, endTime);

        //根据条件查询分页数据
        Page<Orders> pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(number!=null,Orders::getNumber,number);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        if (beginTime!=null&&endTime!=null) {
            queryWrapper.between(Orders::getOrderTime, beginTime, endTime);
        }
        orderService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改派送状态
     *
     * @param order
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders order){
        log.info("修改数据：{}",order);

//        Orders orders = orderService.getById(order);
//
//        orders.setStatus(orders.);


//        if(order.getStatus() == 1){
//            order.setStatus(2);
//        }
//        if(order.getStatus() == 3){
//            order.setStatus(4);
//        }

        orderService.updateById(order);
        return R.success("修改成功");
    }


    /**
     * 订单详情
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        log.info("page={},pageSize={]", page, pageSize);

        //新建分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);

        //新建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行过滤条件
        orderService.page(pageInfo, queryWrapper);

        //对象拷贝
        Page<OrdersDto> ordersDtoPage = new Page<>();

        //分页对象拷贝
        BeanUtils.copyProperties(pageInfo, ordersDtoPage);

        //处理分页集合
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            //新建订单Dto
            OrdersDto ordersDto = new OrdersDto();

            //对象拷贝
            BeanUtils.copyProperties(item, ordersDto);

            //根据任意对象userId获取订单详情
            Long orderId = item.getId();

            //新建条件构造器
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            //添加过滤条件
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);

            //根过滤条件获取菜品集合
            List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);

            //把菜品集合塞入dto中
            ordersDto.setOrderDetails(orderDetails);

            return ordersDto;


        }).collect(Collectors.toList());


        //将dto集合塞到分页查询里
        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);

    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        log.info(orders.toString());

        //根据id获取订单对象
        Orders order = orderService.getById(orders);

        //添加条件构造器
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.eq(OrderDetail::getOrderId, order.getId());

        //根据过滤条件求出菜品详情集合
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //把菜品拷贝到购物车对象中
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //创建购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();

            //进行对象拷贝
            BeanUtils.copyProperties(item, shoppingCart, "id", "OrderId");

            //对购物车中为赋值的地方进行赋值
            shoppingCart.setUserId(order.getUserId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;

        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("下单成功");

    }


    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据:{}", orders);

        orderService.submit(orders);

        return R.success("下单成功");

    }


}